package ds_industry_2025.ds.ds01.T1

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.lit

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}
/*
      6、抽取shtd_store库中order_detail的增量数据进入Hive的ods库中表order_detail，根据ods.order_detail表中create_time
      作为增量字段，只将新增的数据抽入，字段名称、类型不变，同时添加静态分区，分区字段为etl_date，类型为String，且值为当前比赛日
      的前一天日期（分区字段格式为yyyyMMdd）。使用hive cli执行show partitions ods.order_detail命令，将结果截图粘贴至客户
      端桌面【Release\任务B提交结果.docx】中对应的任务序号下。
 */
object t6 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t6")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val conn = new Properties()
    conn.setProperty("user", "root")
    conn.setProperty("password", "123456")
    conn.setProperty("driver", "com.mysql.jdbc.Driver")

    val day=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)

    spark.table("ods.order_detail").createOrReplaceTempView("ods")

    val max_time = spark.sql("select max(create_time) from ods").collect()(0).get(0).toString

    spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_store?useSSL=false","order_detail",conn)
      .createOrReplaceTempView("mysql")

    val result = spark.sql(
      s"""
         |select * from mysql  where  create_time > cast('$max_time' as timestamp)
         |""".stripMargin)

    result.withColumn("etl_date",lit(yesterday))
      .write.mode("append")
      .partitionBy("etl_date")
      .saveAsTable("ods.order_detail")







    spark.close()
  }

}
